package org.black.phoneUtility.app.activity;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

import org.black.phoneUtility.PhoneUtilityConstant;
import org.black.phoneUtility.R;
import org.black.phoneUtility.app.fragment.BackupFileExploreFragment;
import org.black.phoneUtility.database.sqlite.PhoneUtilitySQLiteOpenHelper;
import org.black.phoneUtility.util.database.backupRestore.BackupRestoreUtility;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class BackupActivity extends Activity {
	private static final String LOG_TAG = BackupActivity.class.getName();
	private static final int REQUEST_CODE_FOR_BACKUP_FOLDER_PATH = 16386;
	private String currentFolderPath = null;

	private ProgressDialog backupProgressDialog = null;

	private AlertDialog.Builder resultBuilder = null;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_FOR_BACKUP_FOLDER_PATH) {
			if (data != null) {
				String filePath = data
						.getStringExtra(BackupFileExploreFragment.RESULT_CURRENT_FILE_PATH);
				if (TextUtils.isEmpty(filePath) == false) {
					currentFolderPath = filePath;
					((Button) findViewById(R.id.backupMainFolderButton))
							.setText(currentFolderPath);
				}
			}
		}
	}

	@Override
	public void onBackPressed() {
		this.finish();
		this.overridePendingTransition(R.animator.left_slide_enter,
				R.animator.left_slide_exit);
	}

	@Override
	public void onContentChanged() {
		super.onContentChanged();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getActionBar().setDisplayHomeAsUpEnabled(true);
		setTitle(R.string.backup_main_title);
		setContentView(R.layout.backup_main);
		Button backupMainFolderButton = (Button) findViewById(R.id.backupMainFolderButton);
		backupMainFolderButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(BackupActivity.this,
						BackupFileExploreActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString(BackupFileExploreActivity.ARGUMENTS_FILE_PATH,
						currentFolderPath);
				intent.putExtras(bundle);
				startActivityForResult(intent,
						REQUEST_CODE_FOR_BACKUP_FOLDER_PATH);
				overridePendingTransition(R.animator.right_slide_enter,
						R.animator.right_slide_exit);
			}
		});
		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		String filePath = sharedPreferences
				.getString(
						getString(R.string.preference_backup_and_restore_the_last_backup_folder_path),
						null);
		if (currentFolderPath == null) {
			File folder = null;
			if (TextUtils.isEmpty(filePath) == true) {
				folder = Environment
						.getExternalStoragePublicDirectory(PhoneUtilityConstant.ROOT_FOLDER_NAME);
				folder.mkdir();
			} else {
				folder = new File(filePath);
			}
			if (folder.isDirectory() == false) {
				folder = folder.getParentFile();
			}
			if (folder == null) {
				folder = Environment
						.getExternalStoragePublicDirectory(PhoneUtilityConstant.ROOT_FOLDER_NAME);
				folder.mkdir();
			}
			currentFolderPath = folder.getAbsolutePath();
		}
		String fileName = getDefaultFileName();
		EditText backupAddEditFileNameDialogMessageEditText = (EditText) findViewById(R.id.backupMainBackupFileNameEditText);
		backupAddEditFileNameDialogMessageEditText.setText(fileName);
		Button backupMainBackupButton = (Button) findViewById(R.id.backupMainBackUpButton);
		backupMainBackupButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				backupProgressDialog.show();
				EditText backupAddEditFileNameDialogMessageEditText = (EditText) findViewById(R.id.backupMainBackupFileNameEditText);
				String fileName = backupAddEditFileNameDialogMessageEditText
						.getEditableText().toString();
				if (TextUtils.isEmpty(fileName) == true) {
					fileName = getDefaultFileName();
				}
				File currentFolder = new File(currentFolderPath);
				if (currentFolder.isDirectory() == false) {
					currentFolder = currentFolder.getParentFile();
				}
				if (currentFolder == null) {
					currentFolder = Environment
							.getExternalStoragePublicDirectory(PhoneUtilityConstant.ROOT_FOLDER_NAME);
					currentFolder.mkdir();
				}

				CheckBox backupOptionsSmsReplyCheckBox = (CheckBox) findViewById(R.id.backupMainBackupOptionsSmsReplyCheckBox);
				boolean backupSmsReply = backupOptionsSmsReplyCheckBox
						.isChecked();

				CheckBox backupOptionsSmsScheduleCheckBox = (CheckBox) findViewById(R.id.backupMainBackupOptionsSmsScheduleCheckBox);
				boolean backupSmsSchedule = backupOptionsSmsScheduleCheckBox
						.isChecked();

				File newFile = new File(currentFolder, fileName);
				File databaseFile = getDatabasePath(PhoneUtilitySQLiteOpenHelper.DATABASE_NAME);

				try {
					BackupRestoreUtility.backupDatabase(BackupActivity.this,
							databaseFile, newFile, true, backupSmsReply,
							backupSmsSchedule);
				} catch (IOException e) {
					Log.e(LOG_TAG, "ERROR", e);
				}
				backupProgressDialog.dismiss();

				SharedPreferences sharedPreferences = PreferenceManager
						.getDefaultSharedPreferences(BackupActivity.this);
				sharedPreferences
						.edit()
						.putString(
								getString(R.string.preference_backup_and_restore_the_last_backup_folder_path),
								currentFolder.getAbsolutePath()).commit();
				sharedPreferences
						.edit()
						.putString(
								getString(R.string.preference_backup_and_restore_the_last_backup_file_path),
								newFile.getAbsolutePath()).commit();
				resultBuilder
						.setMessage(R.string.backup_main_backup_result_dialog_backup_complete);
				resultBuilder.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						});
				resultBuilder.show();
			}
		});
		Button backupMainCancelButton = (Button) findViewById(R.id.backupMainCancelButton);
		backupMainCancelButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		this.backupProgressDialog = new ProgressDialog(BackupActivity.this,
				ProgressDialog.STYLE_SPINNER);
		this.backupProgressDialog
				.setTitle(R.string.backup_main_backup_dialog_title);
		this.backupProgressDialog
				.setMessage(getString(R.string.backup_main_backup_dialog_message));
		this.resultBuilder = new AlertDialog.Builder(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Button backupMainFolderButton = (Button) findViewById(R.id.backupMainFolderButton);
		backupMainFolderButton.setText(currentFolderPath);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.backupProgressDialog.cancel();
		this.backupProgressDialog.dismiss();
		this.backupProgressDialog = null;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private String getDefaultFileName() {
		Calendar currentCalendar = Calendar.getInstance();
		String result = "bk_" + currentCalendar.get(Calendar.YEAR)
				+ +currentCalendar.get(Calendar.MONTH)
				+ +currentCalendar.get(Calendar.DAY_OF_MONTH)
				+ +currentCalendar.get(Calendar.HOUR_OF_DAY)
				+ +currentCalendar.get(Calendar.MINUTE)
				+ +currentCalendar.get(Calendar.SECOND) + ".sqlite";
		return result;
	}
}
